<?php
namespace app\applet\model;
use think\Db;
use think\Model;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/5
 * Time: 16:25
 */
class  Repair extends Model
{
    /**
     * 显示用户租住房间
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function repairList($id){
        $types['c_type'] = array('lt',4);
        $user=Db::name('house_keeper')
            ->field('tel')
            ->where(['id'=>$id])
            ->find();
        $arr=[];
        $arr['tel']=$user['tel'];
        //查询所有有效合同
        $data=Db::name('tenant_management')
            ->field('b.t_c_mid,c.c_id')
            ->alias('a')
            ->where(['a.tenant_user_id'=>$id])
            ->join('tenant_contract b','b.t_id=a.tenant_id')
            ->join('contract_management c','b.t_c_mid=c.c_id')
            ->where($types)
            ->select();
        $i=[];
        //合同住房
        foreach ($data as $k=>$v){
            $i[]=Db::name('contracted_housing')
                ->where(['c_c_mid'=>$v['c_id']])
                ->select();
        }
        //三维数组变二维
        $newhello=[];
        $k=0;
        foreach ($i as $key => $val) {
            foreach ($val as $key2 => $val2) {
                $newhello[$k]['h_id'] = $val2 ['h_id'];
                $newhello[$k]['c_number'] = $val2['c_number'];
                $newhello[$k]['h_type'] = $val2['h_type'];
                $k++;
            }
        }
        //排序
        array_multisort(array_column($newhello, 'c_number'),SORT_ASC,$newhello);
        $arr['housing']=$newhello;
        return $arr;
    }


    /**
     * 报修添加
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function repairAdd($data){
        //处理数据查找房源的单元栋等信息
        if($data['type']==1){
            $i=Db::name('housing_information')
                ->field('create_id,h_tung_num,h_unit_num,h_layer_num,h_room_number')
                ->where(['housing_id'=>$data['house_id']])
                ->find();
            $arr['admin_id']=$i['create_id'];
            $arr['tung_num']=$i['h_tung_num'];
            $arr['unit_num']=$i['h_unit_num'];
            $arr['layer_num']=$i['h_layer_num'];
            $arr['room_num']=$i['h_room_number'];
        }else{
            $i=Db::name('shops')
                ->field('create_id,s_tung_num,s_unit_num,s_layer_num,s_room_number')
                ->where(['shops_id'=>$data['house_id']])
                ->find();
            $arr['admin_id']=$i['create_id'];
            $arr['tung_num']=$i['s_tung_num'];
            $arr['unit_num']=$i['s_unit_num'];
            $arr['layer_num']=$i['s_layer_num'];
            $arr['room_num']=$i['s_room_number'];
        }
        //查找租客信息
        $user=Db::name('tenant_management')
            ->field('tenant_name,tenant_tel')
            ->where(['tenant_user_id'=> $data['user_id']])
            ->find();
        if($user!=null){
            $arr['tenant_name']=$user['tenant_name'];
        }
        $arr['user_id'] = isset($data['user_id']) ? trim($data['user_id']) : "";
        $arr['remark'] = isset($data['remark']) ? trim($data['remark']) : "";
        $arr['tenant_tel'] = isset($data['tel']) ? trim($data['tel']) : "";
        $arr['house_id'] = isset($data['house_id']) ? trim($data['house_id']) : "";
        $arr['type'] = isset($data['type']) ? trim($data['type']) : "";
        $arr['room_number'] = isset($data['room_number']) ? trim($data['room_number']) : "";
        $arr['title'] = isset($data['title']) ? trim($data['title']) : "";
        $arr['image'] = isset($data['image']) ? implode(',',$data['image']): "";
        $arr['create_time'] = time();
        $datas=Db::name('repair')->insertGetId($arr);
        if($datas){
            //消息推送给员工
            //权限表
            $action=Db::name('action')->where(['id'=>121])->find();
           // $where['action_id'] = ['like',"%".','.$action['id'].','."%"];
            //模糊查询权限角色表
            $where['action_id'] = ['like',"%".$action['id']."%"];
            $role=Db::name('role_action')->field('role_id')->where($where)->select();
            $count=[];
            //循环拿到权限对应员工
            foreach ($role as $k=>$v){
                $date=Db::name('admin_user')
                    ->where(['create_id'=>$arr['admin_id']])
                    ->where(['role_id'=>$v['role_id']])
                    ->select();
                if($date!=null){
                    $count[]=$date;
                }
            }
            $i['first']='有新的报修通知，请查看。';
            $i['keyword1']=$arr['room_number'];
            $i['keyword2']=$arr['tenant_tel'];
            $i['keyword3']=$arr['title'];
            $i['keyword4']=date('Y-m-d H:i:s',time());
            $i['remark']='请尽快处理报修任务。';
            $i['url']='pages/index/repair/repairDetail/repairDetail?id='.$datas.'&type=1';
            foreach ($count as $key=>$val){
                foreach ($val as $k=>$v){
                    if($v['wechat_open_id']!=null){
                        $i['openid']=$v['wechat_open_id'];
                        $this->WechatThree($i);
                    }
                }
            }
        }
        return $datas;
    }
    /**
    * 修改显示数据
    * @return false|\PDOStatement|string|\think\Collection
    */
    public function repairOne($data){
        $user=Db::name('repair')
            ->field('repair_id,room_number,title,remark,image,tenant_tel')
            ->where(['repair_id'=>$data['repair_id']])
            ->find();
        if($user['image']!=null){
            $user['image'] = explode(',', $user['image']);
           // $user['image']=$this->dealImage($user['image']);
        }
        return $user;
    }
    /**
     * 报修修改提交
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function repairEdit($data){
        $where['repair_id'] = $data['repair_id'];
        $arr['remark'] = isset($data['remark']) ? trim($data['remark']) : "";
        $arr['tenant_tel'] = isset($data['tel']) ? trim($data['tel']) : "";
        $arr['title'] = isset($data['title']) ? trim($data['title']) : "";
        $arr['image'] = isset($data['image']) ? implode(',',$data['image']): "";
        $datas=Db::name('repair')->where($where)->update($arr);
        return $datas;
    }
    /**
     * 报修列表
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function repairIndex($data){
        $page=isset($data['p']) ? trim($data['p']) : 1;
        $status=isset($data['status']) ? trim($data['status']) : 2;
        $where=[];
        $where['status']=$status;
        $where['user_id']=$data['id'];
        $count=Db::name('repair')
            ->where($where)
            ->count();
        $datas=Db::name('repair')
            ->field('repair_id,room_number,title,image,create_time')
            ->where($where)
            ->page($page, 10)
            ->order("over_time desc,create_time desc")
            ->select();
        $nomore=Db::name('repair')
            ->field('repair_id,room_number,title,image,create_time')
            ->where($where)
            ->page($page+1, 10)
            ->order("over_time desc,create_time desc")
            ->select();
        if($nomore==null){
            $nomore=true;
        }else{
            $nomore=false;
        }
        if($datas!=null){
            foreach ($datas as $k=>$v){
                $datas[$k]['create_time']=date('Y-m-d H:i:s',$v['create_time']);
                if($v['image']!=null){
                    $datas[$k]['image']=$this->dealImage($v['image']);
                }
            }
        }
        $zf=$this->repairList($data['id']);
        //var_dump($zf);exit;
        if($zf['housing']==null){
            $i['code']=2;
        }elseif($datas==null){
            $i['code']=3;
        }else{
            $i['code']=1;
        }
        $i['data']=$datas;
        $i['no_more']=$nomore;
        $i['count']=$count;
        return $i;
    }
    /**
     * 报修查看
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function repairDetails($data){
        $user=Db::name('repair')
            ->field('repair_id,room_number,title,remark,image,tenant_tel,create_time,maintenance_id,status')
            ->where(['repair_id'=>$data['repair_id']])
            ->find();
        $user['create_time']=date('Y-m-d H:i:s',$user['create_time']);
        $user['user']=Db::name('admin_user')
            ->field('admin_id,name,admin_tel,department_name,job_number')
            ->where(['admin_id'=>$user['maintenance_id']])
            ->find();
        $repair=Db::name('maintenance_records')
            ->where(['r_id'=>$user['repair_id']])
            ->select();
        foreach($repair as $k=>$v){
            $repair[$k]['m_deal_time']=date('Y-m-d H:i:s',$v['m_deal_time']);
            $repair[$k]['m_image']=$this->dealImage($v['m_image']);
        }
        $user['records']=$repair;
        if($user['image']!=null){
            $user['image']=$this->dealImage($user['image']);
        }
        return $user;
    }
    /**
     * 报修二次提交
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function submission($data){
        $where['repair_id'] = $data['repair_id'];
        $i=Db::name('repair')->where($where)->find();
        $arr['admin_id']=$i['admin_id'];
        $arr['tung_num']=$i['tung_num'];
        $arr['unit_num']=$i['unit_num'];
        $arr['layer_num']=$i['layer_num'];
        $arr['room_num']=$i['room_num'];
        $arr['type'] =$i['type'];
        $arr['user_id'] =$i['user_id'];
        $arr['house_id'] =$i['house_id'];
        $arr['tenant_name']=$i['tenant_name'];
        $arr['room_number']=$i['room_number'];

        $arr['tenant_tel'] = isset($data['tel']) ? trim($data['tel']) : "";
        $arr['remark'] = isset($data['remark']) ? trim($data['remark']) : "";
        $arr['title'] = isset($data['title']) ? trim($data['title']) : "";
        if($data['image']!=''){
            $arr['image'] = isset($data['image']) ? implode(',',$data['image']): "";
        }
        $arr['create_time'] = time();

        $datas=Db::name('repair')->insert($arr);
        return $datas;
    }


    /**
     * 员工端报修列表
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function staffRepair($data){
        $page=isset($data['p']) ? trim($data['p']) : 1;
        $status=isset($data['status']) ? trim($data['status']) : 2;
        $where=[];
        if($status!=2){
            $where['a.maintenance_id']=$data['id'];
        }
        $model=new \app\manage\model\UserRole();
        $where['a.admin_id']= $model->create_id($data['id']);
        $where['a.status']=$status;
        $count=Db::name('repair')
            ->alias('a')
            ->join('house_keeper b','b.id=a.user_id')
            ->where($where)
            ->count();
        $datas=Db::name('repair')
            ->alias('a')
            ->join('house_keeper b','b.id=a.user_id')
            ->field('a.repair_id,a.room_number,a.title,a.image,a.create_time,a.tenant_tel,a.tenant_name,b.icon')
            ->where($where)
            ->page($page, 10)
            ->order("a.over_time desc,a.create_time desc")
            ->select();
        $nomore=Db::name('repair')
            ->alias('a')
            ->join('house_keeper b','b.id=a.user_id')
            ->field('a.repair_id,a.room_number,a.title,a.image,a.create_time,a.tenant_tel,a.tenant_name,b.icon')
            ->where($where)
            ->page($page+1, 10)
            ->order("a.over_time desc,a.create_time desc")
            ->select();
        if($nomore==null){
            $nomore=true;
        }else{
            $nomore=false;
        }
        if($datas!=null){
            foreach ($datas as $k=>$v){
                $datas[$k]['create_time']=date('Y-m-d H:i:s',$v['create_time']);
                if($v['image']!=null){
                    $datas[$k]['image']=$this->dealImage($v['image']);
                }
            }
        }
        $i['no_more']=$nomore;
        $i['data']=$datas;
        $i['count']=$count;
        return $i;
    }

    /**
     * 员工端报修领取
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function receiveTasks($data){
        $count['maintenance_id']=$data['id'];
        $count['status']=3;
        $count['deal_time']=time();
        $i=Db::name('repair')->where(['repair_id'=>$data['repair_id']])->find();
        if($i['status']==3){
            return 2;
        }
        $datas=Db::name('repair')->where(['repair_id'=>$data['repair_id']])->update($count);
        $dates=null;
        $page=isset($data['p']) ? trim($data['p']) : '';
        if($page!=''){
            //返回数据
            $where['a.status']=2;
            $count=Db::name('repair')
                ->alias('a')
                ->join('house_keeper b','b.id=a.user_id')
                ->field('a.repair_id,a.room_number,a.title,a.image,a.create_time,a.tenant_tel,a.tenant_name,b.icon')
                ->where($where)
                ->page($page, 10)
                ->select();
            $count=count($count);
            if($count==10){
                $dates=Db::name('repair')
                    ->alias('a')
                    ->join('house_keeper b','b.id=a.user_id')
                    ->field('a.repair_id,a.room_number,a.title,a.image,a.create_time,a.tenant_tel,a.tenant_name,b.icon')
                    ->where($where)
                    ->page($page, 10)
                    ->order("a.over_time desc,a.create_time desc")
                    ->select();
                $dates=$dates[9];
                $dates['create_time']=date('Y-m-d H:i:s',$dates['create_time']);
                if($dates['image']!=null){
                    $dates['image']=$this->dealImage($dates['image']);
                }
            }
        }


        //消息推送
        $admin_user=Db::name('admin_user')->where(['admin_id'=>$data['id']])->find();
        $user=Db::name('house_keeper')->where(['id'=>$i['user_id']])->find();
        $data['openid']=$user['wechat_subscription_open_id'];
        if($user['sex']==1){
            $data['first']="尊敬的".$i['tenant_name']."先生，您的报修有新进展";
        }else{
            $data['first']="尊敬的".$i['tenant_name']."女士，您的报修有新进展";
        }
        $data['keyword1']=$i['room_number'];
        $data['keyword2']=$i['title'];
        $data['keyword4']='处理中';
        $data['keyword5']='已安排维修工'.$admin_user['name'].'上门维修，联系电话:'.$admin_user['admin_tel'];
        $data['keyword3']=date('Y-m-d H:i:s',$i['create_time']);//.$data['repair_id']
        $data['url']='pages/mine/repair/repairDetail/repairDetail?id='.$data['repair_id'].'&type=2';
        //var_dump($data['repair_id']);exit;
       // $data['url']='pages/mine/repair/repair';
        $this->Wechat($data);
        return $dates;
    }

    /**
     * 员工报修查看
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function details($data){
        $user=Db::name('repair')
            ->alias('a')
            ->join('house_keeper b','b.id=a.user_id')
            ->field('a.repair_id,a.room_number,a.title,a.remark,a.image,a.tenant_tel,a.create_time,a.maintenance_id,a.status,b.icon,a.tenant_name')
            ->where(['a.repair_id'=>$data['repair_id']])
            ->find();
        $user['create_time']=date('Y-m-d H:i:s',$user['create_time']);
        $repair=Db::name('maintenance_records')
            ->where(['r_id'=>$user['repair_id']])
            ->select();
        if($repair!=null){
            foreach($repair as $k=>$v){
                $repair[$k]['m_deal_time']=date('Y-m-d H:i:s',$v['m_deal_time']);
                if($v['m_image']==null){
                    $repair[$k]['m_image']=[];
                }else{
                    $repair[$k]['m_image']=$this->dealImage($v['m_image']);
                }
            }
        }
        $user['records']=$repair;
        if($user['image']!=null){
           $user['image']=$this->dealImage($user['image']);
        }
        return $user;
    }
    /**
     * 添加维修记录
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function maintenanceRecord($data){
        $arr['m_remark'] = isset($data['remark']) ? trim($data['remark']) : "";
        $arr['m_image'] = isset($data['image']) ? implode(',',$data['image']): "";
        $arr['r_id'] = $data['repair_id'];
        $arr['u_id'] = $data['u_id'];
        $arr['m_deal_time'] = time();
        $repair=Db::name('maintenance_records')->insert($arr);
        return $repair;
    }
    /**
     * 维修记录编辑显示
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function recordEditorOne($data){
        $repair=Db::name('maintenance_records')->where(['m_id'=>$data['m_id']])->find();
        if($repair['m_image']!=null){
            $repair['m_image'] = explode(',', $repair['m_image']);
           // $repair['m_image']= $this->dealImage($repair['m_image']);
        }
        return $repair;
    }
    /**
     * 维修记录编辑提交
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function recordEditor($data){
        $where['m_id']=$data['m_id'];
        $arr['m_remark'] = isset($data['remark']) ? trim($data['remark']) : "";
        $arr['m_image'] = isset($data['image']) ? implode(',',$data['image']): "";
        $repair=Db::name('maintenance_records')->where($where)->update($arr);
        return $repair;
    }
    /**
     * 维修记录编辑提交
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function recordDel($data){
        $where['m_id']=$data['m_id'];
        $repair=Db::name('maintenance_records')->where($where)->delete();
        return $repair;
    }
    /**
     * 维修完成
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function maintenanceCompleted($data){
        $where['repair_id']=$data['repair_id'];
        $arr['status']=1;
        $arr['over_time']=time();
        $repair=Db::name('repair')->where($where)->update($arr);
        $i=Db::name('repair')->where($where)->find();
        $user=Db::name('admin_user')->where(['admin_id'=>$i['maintenance_id']])->find();
        $keeper=Db::name('house_keeper')->where(['id'=>$i['user_id']])->find();
        $coun['first']='尊敬的租客，您的报修已经完成';
        $coun['remark']='点击查看报修情况。';
        $coun['keyword1']=$i['room_number'];
        $coun['keyword2']=$i['title'];
        $coun['keyword3']=$user['name'];
        $coun['openid']=$keeper['wechat_subscription_open_id'];
        $coun['keyword4']=date("Y-m-d",$i['over_time']);
        $coun['url']='pages/mine/repair/repairDetail/repairDetail?id='.$data['repair_id'].'&type=3';
        $this->WechatTwo($coun);
        return $repair;
    }
    /**
     * 处理图像
     * @param $image
     * @return mixed
     */
    private function dealImage($image) {
        $image = explode(',', $image);
        foreach ($image as &$item) {
            $item =  "https://" . $_SERVER['SERVER_NAME'] . $item;
        }
        return $image;
    }
    /**
     * 处理图像
     * @param $image
     * @return mixed
     */
    public function repairOrder($id) {
        $model=new \app\manage\model\UserRole();
        $where['admin_id']= $model->create_id($id);
        $repair=Db::name('repair')->where($where)->count();
        return $repair;
    }

    //领取报修之后消息模板推送
    public function Wechat($data){
        // 微信接口类
        $WeChat = new  \Template\Wechat();
        $weiwei_token = $WeChat->getToken(); // 获取微信token
        # 公众号消息推送"path":"pages/Discuss/DiscussInfo/DiscussInfo?DicGroupId=39"
        $WeChat::pushMessage([
            'miniprogram'=> [
                'appid' =>'wx86ab83e50e851d0c',
                'pagepath' =>$data['url'],
            ],
            'template_id' => "DkSJGBKxDObQKIVM1ssvThm6eQh-q17rhrGwGZS7qZE", // 填写你自己的消息模板ID
            'openid' => $data['openid'], // 用户openid
            'access_token' => $weiwei_token,
            'data' => [ // 模板消息内容，根据模板详情进行设置
                'first'    => ['value' => urlencode($data['first']),'color' => "#743A3A"],
                'keyword1' => ['value' => urlencode($data['keyword1']),'color'=>''],
                'keyword2' => ['value' => urlencode($data['keyword2']),'color'=>''],
                'keyword3' => ['value' => urlencode($data['keyword3']),'color' => ''],
                'keyword4' => ['value' => urlencode($data['keyword4']),'color' => ''],
                'keyword5' => ['value' => urlencode($data['keyword5']),'color' => ''],
                'remark'   => ['value' => urlencode("如有疑问可联系维修工"),'color' => '#743A3A']
            ],
        ]);
       // var_dump($i);exit;
    }
    //报修完成之后消息推送
    public function WechatTwo($data){
        // 微信接口类
        $WeChat = new  \Template\Wechat();
        $weiwei_token = $WeChat->getToken(); // 获取微信token
        # 公众号消息推送
        $WeChat::pushMessage([
            'miniprogram'=> [
                'appid' =>'wx9eca16e65fdc2aa4',
                'pagepath' =>$data['url'],
            ],
            'openid' => $data['openid'], // 用户openid
            'access_token' => $weiwei_token,
            'template_id' => "5AObhd2uPv7tVrlA6J05vxlT_-qi5sNPPYs0iAXTym0", // 填写你自己的消息模板ID
            'data' => [ // 模板消息内容，根据模板详情进行设置
                'first'    => ['value' => urlencode($data['first']),'color' => "#743A3A"],
                'keyword1' => ['value' => urlencode($data['keyword1']),'color'=>''],
                'keyword2' => ['value' => urlencode($data['keyword2']),'color'=>''],
                'keyword3' => ['value' => urlencode($data['keyword3']),'color' => ''],
                'keyword4' => ['value' => urlencode($data['keyword4']),'color' => ''],
                'remark'   => ['value' => urlencode($data['remark']),'color' => '#743A3A']
            ],
        ]);
    }
    //报修内容推送给员工
    public function WechatThree($data){
        // 微信接口类
        $WeChat = new  \Template\Wechat();
        $weiwei_token = $WeChat->getToken(); // 获取微信token
        # 公众号消息推送
        $WeChat::pushMessage([
            'miniprogram'=> [
                'appid' =>'wx9eca16e65fdc2aa4',
                'pagepath' =>$data['url'],
            ],
            'openid' => $data['openid'], // 用户openid
            'access_token' => $weiwei_token,
            'template_id' => "DLSoCjgBQqG43cNjOn99pOYMwi6G5QLNFygrcR0-37I", // 填写你自己的消息模板ID
            'data' => [ // 模板消息内容，根据模板详情进行设置
                'first'    => ['value' => urlencode($data['first']),'color' => "#743A3A"],
                'keyword1' => ['value' => urlencode($data['keyword1']),'color'=>''],
                'keyword2' => ['value' => urlencode($data['keyword2']),'color'=>''],
                'keyword3' => ['value' => urlencode($data['keyword3']),'color' => ''],
                'keyword4' => ['value' => urlencode($data['keyword4']),'color' => ''],
                'remark'   => ['value' => urlencode($data['remark']),'color' => '#743A3A']
            ],
        ]);
    }
}